(function(){
var db = require("../../core/db/index");
var config = require("../../core/_include/config");

var BusCon = require("../../core/bus/_con");
var UserCon = require("../../core/user/_con");
var AdminCon = require("../../core/admin/_con");
var role = {
	getUser:function(app){
		var loginerHash = app.cookies.get("loginSession");
		var loginInfo = db.find_by_id(config.dbname.loginHash,loginerHash);
		if (loginInfo) {
			if ((loginInfo.time+config.autoSignUpTime)<+new Date) {
				db.remove(config.dbname.loginHash,loginerHash);
				throw "登录超时，请重新登录";
			}else if(loginInfo.type!=="user"){
				throw "cookie值无效";
			}else{
				return UserCon.get(loginInfo.user_id)
			}
		}else{
			throw "客户端未登录";
		}
	},
	getBus:function(app){
		var loginerHash = app.cookies.get("loginSession");
		var loginInfo = db.find_by_id(config.dbname.loginHash,loginerHash);
		if (loginInfo) {
			if ((loginInfo.time+config.autoSignUpTime)<+new Date) {
				db.remove(config.dbname.loginHash,loginerHash);
				throw "登录超时，请重新登录";
			}else if(loginInfo.type!=="bus"){
				throw "cookie值无效";
			}else{
				return BusCon.get(loginInfo.bus_id)
			}
		}else{
			throw "客户端未登录";
		}
	},
	getAdmin:function(app){
		var loginerHash = app.cookies.get("loginSession");
		var loginInfo = db.find_by_id(config.dbname.loginHash,loginerHash);
		if (loginInfo) {
			if ((loginInfo.time+config.autoSignUpTime)<+new Date) {
				db.remove(config.dbname.loginHash,loginerHash);
				throw "登录超时，请重新登录";
			}else if(loginInfo.type!=="admin"){
				throw "cookie值无效";
			}else{
				return AdminCon.get(loginInfo.admin_id)
			}
		}else{
			throw "客户端未登录";
		}
	},
	checkRole:function(type,app){
		var loginerHash = app.cookies.get("loginSession");
		var loginInfo = db.find_by_id(config.dbname.loginHash,loginerHash);
		console.log("loginInfo:",loginInfo);
		if (loginInfo) {
			switch(type){
				case "user":
					return loginInfo.type===type||loginInfo.type==="admin";
				case "bus":
					return loginInfo.type===type||loginInfo.type==="admin";
				default:
					return loginInfo.type==="admin";
			}
		}else{
			throw "客户端未登录";
		}
	},
	resCheckRole:function(type,app){
		console.log("权限检查！",type);
		var ResponObj = require("../_include/ResponObj");
		try{
			if (!type) {
				throw "参数错误";
			}else if (role.checkRole(type,app)) {
				//拥有足够的权限，继续运行
			}else{
				throw "权限不足";
			}
			return true;
		}catch(e){
			app.body = ResponObj("error",e);
			// throw "用户权限检查结束，中断："+e;
			return false;
		}
	}
};
module.exports = role;
}());